<?php

include_once "quickcrud_connect.php";
include_once "quickcrud_common.php";
include "CF_mysql_com.php";
include_once "CF_all_com.php";

// CT 2009-02-27 - Added classlib_path as subpath for createion of common elements.  Also added jscalendar subdirectory

if (!isset($_REQUEST['project_id'])  ){
	print 'Please select or create a project first';
	print "<a href='switchboard.php?project_id=$project_id'> Back to Switchboard</a>";
	exit;
}

	$project_id = $_REQUEST['project_id'];


	$qry_project_info = "SELECT * FROM projects WHERE project_id = $project_id";

	$project_info = get_array_query($qry_project_info);
	$project_db = $project_info[1]['project_db'];
	$project_path = $project_info[1]['project_path'];
	$project_server = $project_info[1]['project_server'];
	$project_login = $project_info[1]['project_login'];
	$project_pass = $project_info[1]['project_pass'];
    $project_name = $project_info[1]['project_name'];
	$class_subpath = $project_info[1]['class_subpath'];
	$template_dir = $project_info[1]['template_dir'];
	
    // This will be the path without the last slash
    $project_path = PROJECT_SUBPATH . $project_path;


	//print_r($project_info);
	
// if path not exists, create
	if(!file_exists($project_path))
	{
		mkdir($project_path);
	}

// copy over sitereg directory
	$sitereg_path = $project_path . '/' . 'sitereg';
	if(!file_exists($sitereg_path))
	{
		mkdir($sitereg_path);
	}
	smartCopy('sitereg/',$sitereg_path);

// Prepare regsettings file

$str_regsettings = "<?php

define('REG_DATABASE', '$project_db'); // Set database name
define('REG_USER', '$project_login'); // Set database name
define('REG_PASS', '$project_pass'); // Set database name
define('REG_USER_TABLE', 'users'); // set name of users table (not tested besides users)
define('REG_USERS_PAGES', 'users_pages'); // set name of users to pages relation table (not tested besides users_pages)
define('REG_ROLE_TABLE', 'roles'); // Set table to describe roles, optional since only ids are used
define('REG_DIRECTORY', 'sitereg/'); // Set to subdirectory where registration stuff is kept 
define('REG_SITE_NAME', '$project_name'); // Set to site name
define('REG_PAGE_AFTERREG', '../');  // go to this page after registeration or details changed


define('REG_PI_SUBDIR', 'reg_inc_page/'); // include directory for page includes 
define('REG_MAILER_DIR', 'PHPMailer/'); // directory to point to php mailer directory

define('REG_DEFAULTPAGE', '../'); // enter page to go to after login, relative to login.php (in sitereg directory)
define('REG_MSG_BADLOGIN', 'The username or password provided was incorrect.  Please try again.');

define('REG_CF_SUBDIR', '../CFClass/'); // include directory for page includes 

define('REG_CONNECT_FILE','../" . $project_name . "_connect.php'); // File that opens mysql connection
define('REG_QUERY_FILE','../CFClass/CF_pdo_com.php'); // File that defines functions lookup_value() and get_array_query()

// Use this to re-direct login to use ssl for login and registration pages.
define('REG_SSL_PORT', '443'); // SSL port for secure conneciton.  
define('REG_USE_SSL', true);

// Set the message for the email with username or password.  Username or password will be output immidatatly following this mesage
// Set the other mail settings in the mail_settings.php file
define('REG_MSG_USERNAME', 'The username associated with this email is: ');
define('REG_MSG_PASSWORD', 'Use this temporary password to login.  It will expire in 24 hours. Password is: ');
define('REG_ROLE_DEFAULT', 2);  // Default user ID, set to 2 for default user
define('REG_PAGES_TABLE', 'pages'); // Default name of pages table
define('REG_USERS_ROLES', 'users_roles'); // Default name of users_roles table
define('REG_ROLES_PAGES', 'roles_pages'); // Default name of roles_pages table
define('REG_ROLES_TABLE', 'roles'); // Default name of roles_pages table


// Pages for self-registration
// Show all or page name.  Value = access level (role_id)
\$reg_DefaultPages['all'] = 1;

?>";	
file_put_contents($sitereg_path . '/regsettings.php',$str_regsettings);	
	
//	
include_once $sitereg_path . "/regsettings.php";	
	
// create tables
// CONNECT TO NEW DB INSTANCE using MySql driver

	$workdb = mysql_connect($project_server, $project_login, $project_pass) or die(mysql_error());
	//print "Got to here 3";
	mysql_select_db($project_db,$workdb)  or die(mysql_error());


$query1="CREATE TABLE `" . REG_USER_TABLE . "` (
  `user_id` int(10) unsigned NOT NULL auto_increment,
  `username` varchar(45) NOT NULL COMMENT 'login name',
  `password` varchar(32) default NULL COMMENT 'main acocunt password',
  `firstname` varchar(45) default NULL COMMENT 'User first name',
  `lastname` varchar(45) default NULL COMMENT 'User Last name',
  `email` varchar(127) default NULL COMMENT 'email for account retrieval',
  `temp_pass` varchar(45) default NULL COMMENT 'temporary password for account retrieval',
  `temp_expire_date` datetime default '2008-01-01 00:00:00' COMMENT 'expiration date for temporary password',
  `question` varchar(255) default NULL COMMENT 'Challenge question',
  `answer` varchar(45) default NULL COMMENT 'Challenge Answer',
  `created_date` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  `last_login_date` timestamp NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (`user_id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
";
mysql_query($query1, $workdb);

$query2="INSERT INTO `" . REG_USER_TABLE . "` (`user_id`,`username`,`password`,`firstname`,`lastname`,`email`,`temp_pass`,`temp_expire_date`,`question`,`answer`,`created_date`,`last_login_date`) VALUES 
 (1,'admin','bffc5260075497528fe6255ab7d91f71','DefaultAdmin','Default admin','admin@nowhere.com',NULL,'2008-01-01 00:00:00',NULL,NULL,'2009-05-09 20:39:41','0000-00-00 00:00:00'),
 (2, 'default', 'bffc5260075497528fe6255ab7d91f71', 'Default', 'User', 'nothing@nowhere.com', '', '2009-10-19 21:58:01', NULL, NULL, '2009-10-21 21:20:36', '2009-10-18 22:00:24');
";
mysql_query($query2, $workdb);


$query5 = "CREATE TABLE IF NOT EXISTS `" . REG_PAGES_TABLE . "` (
  `page_name` varchar(255) NOT NULL,
  `shown` tinyint(4) NOT NULL DEFAULT '1',
  PRIMARY KEY (`page_name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
mysql_query($query5, $workdb);

$query6 = "INSERT INTO `" . REG_PAGES_TABLE . "` (`page_name`, `shown`) VALUES
('all', 1);";
mysql_query($query6, $workdb);



$query7 = "CREATE TABLE IF NOT EXISTS `" . REG_USERS_ROLES . "` (
  `user_id` int(11) NOT NULL,
  `role_id` int(11) NOT NULL,
  PRIMARY KEY (`user_id`,`role_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
mysql_query($query7, $workdb);

$query7 = "INSERT INTO `" . REG_USERS_ROLES . "` (`user_id`, `role_id`) VALUES ('1', '1'), ('2', '2');";
mysql_query($query7, $workdb);

$query3="CREATE TABLE `" . REG_ROLES_PAGES . "` (
  `role_id` int(11) NOT NULL,
  `page_name` varchar(255) NOT NULL,
  `permission` varchar(45) NOT NULL default 'RW',
  PRIMARY KEY  (`role_id`,`page_name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
";
mysql_query($query3, $workdb);

$query3="INSERT INTO `" . REG_ROLES_PAGES . "` (`role_id`, `page_name`, `permission`) VALUES
(1, 'all', 'RW'),
(2, 'all', 'RW');";
mysql_query($query3, $workdb);

$query4 = "CREATE TABLE IF NOT EXISTS `" . REG_ROLE_TABLE . "` (
  `role_id` int(11) NOT NULL AUTO_INCREMENT,
  `role_name` varchar(50) NOT NULL,
  `role_description` varchar(255) NOT NULL,
  PRIMARY KEY (`role_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;";
mysql_query($query4, $workdb);


$query4 = "INSERT INTO `" . REG_ROLES_TABLE . "` (`role_id`, `role_name`, `role_description`) VALUES
(1, 'admin', 'default administrative user with all permissions'),
(2, 'default', 'default user for new users');";
mysql_query($query4, $workdb);

mysql_close($workdb);

// End insert tables



	$result = urlencode($result);
	$header_text = "Location: leftmenu.php?project_id=$project_id&result=$result";
	header($header_text); /* Redirect browser */
	exit;

/**
     * Copy file or folder from source to destination, it can do
     * recursive copy as well and is very smart
     * It recursively creates the dest file or directory path if there weren't exists
     * Situtaions :
     * - Src:/home/test/file.txt ,Dst:/home/test/b ,Result:/home/test/b -> If source was file copy file.txt name with b as name to destination
     * - Src:/home/test/file.txt ,Dst:/home/test/b/ ,Result:/home/test/b/file.txt -> If source was file Creates b directory if does not exsits and copy file.txt into it
     * - Src:/home/test ,Dst:/home/ ,Result:/home/test/** -> If source was directory copy test directory and all of its content into dest     
     * - Src:/home/test/ ,Dst:/home/ ,Result:/home/**-> if source was direcotry copy its content to dest
     * - Src:/home/test ,Dst:/home/test2 ,Result:/home/test2/** -> if source was directoy copy it and its content to dest with test2 as name
     * - Src:/home/test/ ,Dst:/home/test2 ,Result:->/home/test2/** if source was directoy copy it and its content to dest with test2 as name
     * @todo
     *     - Should have rollback technique so it can undo the copy when it wasn't successful
     *  - Auto destination technique should be possible to turn off
     *  - Supporting callback function
     *  - May prevent some issues on shared enviroments : http://us3.php.net/umask
     * @param $source //file or folder
     * @param $dest ///file or folder
     * @param $options //folderPermission,filePermission
     * @return boolean
     */
    function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755))
    {
        $result=false;
       
        if (is_file($source)) {
            if ($dest[strlen($dest)-1]=='/') {
                if (!file_exists($dest)) {
                    cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
                }
                $__dest=$dest."/".basename($source);
            } else {
                $__dest=$dest;
            }
            $result=copy($source, $__dest);
            chmod($__dest,$options['filePermission']);
           
        } elseif(is_dir($source)) {
            if ($dest[strlen($dest)-1]=='/') {
                if ($source[strlen($source)-1]=='/') {
                    //Copy only contents
                } else {
                    //Change parent itself and its contents
                    $dest=$dest.basename($source);
                    @mkdir($dest);
                    chmod($dest,$options['filePermission']);
                }
            } else {
                if ($source[strlen($source)-1]=='/') {
                    //Copy parent directory with new name and all its content
                    @mkdir($dest,$options['folderPermission']);
                    chmod($dest,$options['filePermission']);
                } else {
                    //Copy parent directory with new name and all its content
                    @mkdir($dest,$options['folderPermission']);
                    chmod($dest,$options['filePermission']);
                }
            }

            $dirHandle=opendir($source);
            while($file=readdir($dirHandle))
            {
                if($file!="." && $file!="..")
                {
                     if(!is_dir($source."/".$file)) {
                        $__dest=$dest."/".$file;
                    } else {
                        $__dest=$dest."/".$file;
                    }
                    //echo "$source/$file ||| $__dest<br />";
                    $result=smartCopy($source."/".$file, $__dest, $options);
                }
            }
            closedir($dirHandle);
           
        } else {
            $result=false;
        }
        return $result;
    } 

?>